package cn.com.infohold.smartcity.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.bean.DialogEntity;
import cn.com.infohold.smartcity.bean.DialogFlag;
import cn.com.infohold.smartcity.bean.MultipleEntity;
import cn.com.infohold.smartcity.view.WheelView;


/**
 * Dialog工具类
 * 多选,单选,文本框
 * Created by liangdengke on 2015/8/3.
 */
public final class DialogUtils {
    public static Dialog dialog=null;
    /**
     * 私有化的构造函数, 并且添加throw杜绝反射
     */
    private DialogUtils(){
        throw new RuntimeException("Don't instantiate this class");
    }
    /** 已选标记 */
    private static Set<Integer> selected = new HashSet<>();
    public static void createNewSelectedDialog(final DialogEntity dialogEntity, final WheelView.OnWheelViewOkClickListener onClickListener) {
        createNewSelectedDialog(dialogEntity.getContext(), dialogEntity.getTitle(), onClickListener, dialogEntity.getList(), dialogEntity.getResultStr(), dialogEntity.isMultiChoice(), dialogEntity.isSearchKey(),dialogEntity.isNotNull());
    }
    public static void createNewSelectedDialog(final Context context, String title, final WheelView.OnWheelViewOkClickListener onClickListener, final List<String> items, String defaultValues, final boolean isMultiple, boolean isSearchKey, final boolean isNotNull) {
        CommonUtils.hideSoftInput(context);
        final List<String> showList=new ArrayList<String>();
        final View outerView = LayoutInflater.from(context).inflate(R.layout.dialog_wheel_view, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        TextView titleView = (TextView) outerView.findViewById(R.id.title);
        final EditText searchEditText=(EditText)outerView.findViewById(R.id.search_edit_text);
        final ImageView removeImageView=(ImageView)outerView.findViewById(R.id.remove_input);
        if(isMultiple){
            title="点击选择(多选)";
        }
        titleView.setText(title);
        if (isSearchKey) {
            outerView.findViewById(R.id.search_key).setVisibility(View.VISIBLE);
        } else {
            outerView.findViewById(R.id.search_key).setVisibility(View.GONE);
        }
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNotBlank(s.toString())) {
                    removeImageView.setVisibility(View.VISIBLE);
                    showList.clear();
                    for (String item : items) {
                        if (item.contains(s.toString())) {
                            showList.add(item);
                        }
                    }
                } else {
                    removeImageView.setVisibility(View.GONE);
                    showList.clear();
                    showList.addAll(items);
                }
                wv.setSeletion(0);
                wv.setItems(showList);

            }
        });
        removeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEditText.setText("");
            }
        });
        wv.setSelectTextColor(context.getResources().getColor(R.color.text_title));
        wv.setIsMultiple(isMultiple);

        wv.setSeletion(0);
        if(!isMultiple&&!items.contains("无")&&!isNotNull){
            items.add(0, "无");
        }
        if(items.size()<7){
            wv.setOffset(2);
            wv.setDisplayItemCount(5);
        }else{
            wv.setOffset(3);
            wv.setDisplayItemCount(7);
        }

        if (StringUtils.isBlank(defaultValues)) {
            if(items.size()>3){
                wv.setSeletion(2);
            }else if (items.size()>2){
                wv.setSeletion(1);
            }else{
                wv.setSeletion(0);
            }
        } else {
            if (isMultiple) {
                String[] defaults = defaultValues.split(",");
                List<String> values = new ArrayList<String>();
                for (String s : defaults) {
                    values.add(s);
                }
                wv.setSelectStrs(values);
                wv.setSeletion(0);
            } else {
                if(items.contains(defaultValues)){
                    wv.setSeletion(items.indexOf(defaultValues));
                }else{
                    wv.setSeletion(0);
                }

            }
        }
        showList.addAll(items);

        wv.setItems(items);
        final Dialog dialog = new Dialog(context, R.style.DialogForSelected);
        outerView.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                CommonUtils.hideSoftInput(context);
            }
        });
        outerView.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftInput(context);
                if (!isMultiple) {
                    String result;
                    int selectIndex;
                    if(wv.getSeletedIndex()>showList.size()-1){
                        result="";
                        selectIndex=-1;
                    }else{
                        result = showList.get(wv.getSeletedIndex());
                        if(isNotNull){
                            selectIndex = items.indexOf(result);
                        }else{
                            selectIndex = items.indexOf(result)-1;
                            if (items.indexOf(result) == 0) {
                                result = "";
                            }
                        }

                    }
                    onClickListener.onClick(view, selectIndex, result, null, null);
                } else {
                    List<String> results = wv.getSelectStrs();
                    List<Integer> selectIndexs = new ArrayList<Integer>();
                    List<String> selectValues = new ArrayList<String>();
                    for (String str : items) {
                        if (results.contains(str)) {
                            selectIndexs.add(items.indexOf(str));
                            selectValues.add(str);
                        }
                    }
                    onClickListener.onClick(view, -1, null, selectIndexs, selectValues);
                }
                dialog.dismiss();
            }
        });
        showWheelViewDialog(outerView,dialog);
    }
    /**
     * 呈现WheelView的dialog
     * @param outerView outerView
     * @param dialog dialog
     */
    private static void showWheelViewDialog(final View outerView, Dialog dialog) {
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(outerView);
        final Window mWindow = dialog.getWindow();
        mWindow.setGravity(Gravity.BOTTOM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.FILL_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindow.setAttributes(lp);
        dialog.setCancelable(true);
        final DialogFlag dialogFlag = new DialogFlag();
        outerView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {

                        int heightDiff = outerView.getRootView().getHeight() - outerView.getHeight();
                        if (heightDiff > 200) { // 说明键盘是弹出状态
                            if (dialogFlag.flag) {
                                dialogFlag.flag = false;
                            } else {
                                return;
                            }
                            mWindow.setGravity(Gravity.CENTER);
                        } else if (heightDiff == 0) {
                            if (!dialogFlag.flag) {
                                dialogFlag.flag = true;
                            } else {
                                return;
                            }
                            mWindow.setGravity(Gravity.BOTTOM);
                        }
                    }
                });
        dialog.show();
    }

    /**
     * 创建并显示一个显示的AlertDialog
     * @param context           context
     * @param title             标题,支持富文本 可以为null
     * @param message           信息,支持富文本 可以为null,
     * @param acceptListener    当点击确认后的监听
     */
    public static void createAlertDialog(final Context context,final String title,
                                         final String message,int messageGravity,final String acceptText,final String cancelText, final View.OnClickListener acceptListener,final View.OnClickListener cancelListener){
        final LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = layoutInflater.inflate(R.layout.dialog_create_single_select,null);
        view.findViewById(R.id.list_view).setVisibility(View.GONE);
        TextView messageView = (TextView)view.findViewById(R.id.message);
        TextView titleView = (TextView)view.findViewById(R.id.title);
        messageView.setGravity(messageGravity);
        ImageButton cancelButton = (ImageButton)view.findViewById(R.id.cancel);
        Button okButton = (Button)view.findViewById(R.id.ok);
        if(StringUtils.isNotBlank(acceptText)){
            okButton.setText(acceptText);
        }
        if(StringUtils.isNotBlank(cancelText)){
            //cancelButton.setText(cancelText);
        }

        if(title == null || title.equals("")){
            titleView.setVisibility(View.GONE);
        }else{
            titleView.setText(title);
        }

        if(message == null || message.equals("")){
            messageView.setVisibility(View.GONE);
        }else{
            messageView.setVisibility(View.VISIBLE);
            messageView.setText(message);
        }
        final Dialog dialog = new Dialog(context, R.style.dialog);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setContentView(view, layoutParams);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (acceptListener != null) {
                    acceptListener.onClick(v);
                }
                dialog.dismiss();
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(cancelListener!=null){
                    cancelListener.onClick(v);
                }
                dialog.dismiss();
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (cancelListener != null) {
                    cancelListener.onClick(null);
                }
                Log.i("createAlertDialog", "setOnCancelListener");
            }
        });
        dialog.show();
    }


    public static void createMultiLevelSelectDialog(final Context context, String title, final WheelView.OnWheelViewOkClickListener onClickListener, final List<MultipleEntity> multipleEntityList, String defaultValues) {
        CommonUtils.hideSoftInput(context);
        final List<String> wv1Items = new ArrayList<String>();
        for (MultipleEntity multipleEntity : multipleEntityList) {
            wv1Items.add(multipleEntity.getValue());
        }
        final List<String> wv2Items = new ArrayList<String>();
        if (!multipleEntityList.get(0).getChildren().isEmpty()) {
            for (MultipleEntity multipleEntity : multipleEntityList.get(0).getChildren()) {
                wv2Items.add(multipleEntity.getValue());
            }
        }
        Display mDisplay = ((Activity) context).getWindowManager().getDefaultDisplay();
        int w = mDisplay.getWidth();
        final View outerView = LayoutInflater.from(context).inflate(R.layout.dialog_wheel_view, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        wv.setLayoutParams(new LinearLayout.LayoutParams(w / 2, ViewGroup.LayoutParams.WRAP_CONTENT));
        final WheelView wv2 = (WheelView) outerView.findViewById(R.id.wheel_view_wv2);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(w / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(2, 0, 0, 0);
        wv2.setLayoutParams(layoutParams);
        wv2.setVisibility(View.VISIBLE);
        TextView titleView = (TextView) outerView.findViewById(R.id.title);
        titleView.setText(title);
        wv.setSelectTextColor(context.getResources().getColor(R.color.part_button_common));
        wv2.setSelectTextColor(context.getResources().getColor(R.color.part_button_common));
        wv.setOffset(2);
        wv2.setOffset(2);
//        wv.setSeletion(0);
//        wv2.setSeletion(0);
        if (StringUtils.isBlank(defaultValues)) {
            if(multipleEntityList.size()>3){
                wv.setSeletion(2);
            }else if (multipleEntityList.size()>2){
                wv.setSeletion(1);
            }else{
                wv.setSeletion(0);
            }
            if(multipleEntityList.get(0).getChildren().size()>3){
                wv2.setSeletion(2);
            }else if (multipleEntityList.get(0).getChildren().size()>2){
                wv2.setSeletion(1);
            }else{
                wv2.setSeletion(0);
            }
        }
        if (StringUtils.isNotBlank(defaultValues)) {
            if (defaultValues.contains(",")) {
                String[] strs = defaultValues.split(",");
                if (wv1Items.indexOf(strs[0]) >= 0) {
                    wv.setSeletion(wv1Items.indexOf(strs[0]));
                    MultipleEntity parent = multipleEntityList.get(wv1Items.indexOf(strs[0]));
                    wv2Items.clear();
                    if (!parent.getChildren().isEmpty()) {
                        for (MultipleEntity multipleEntity : parent.getChildren()) {
                            wv2Items.add(multipleEntity.getValue());
                        }
                    }
                    if (wv2Items.indexOf(strs[1]) >= 0) {
                        wv2.setSeletion(wv2Items.indexOf(strs[1]));
                    }
                }
            } else {
                if (wv1Items.indexOf(defaultValues) >= 0) {
                    wv.setSeletion(wv1Items.indexOf(defaultValues));
                }
            }
        }
        wv.setDisplayItemCount(5);
        wv.setItems(wv1Items);
        wv2.setDisplayItemCount(5);
        wv2.setItems(wv2Items);
        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                if (wv1Items.indexOf(item) < 0) {
                    wv2Items.clear();
                    wv2.setItems(wv2Items);
                    return;
                }
                MultipleEntity parent = multipleEntityList.get(wv1Items.indexOf(item));
                wv2Items.clear();
                if (!parent.getChildren().isEmpty()) {
                    for (MultipleEntity multipleEntity : parent.getChildren()) {
                        wv2Items.add(multipleEntity.getValue());
                    }
                }
                wv2.setSeletion(0);
                wv2.setItems(wv2Items);
            }
        });
        final Dialog dialog = new Dialog(context, R.style.DialogForSelected);
        outerView.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                CommonUtils.hideSoftInput(context);
            }
        });
        outerView.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftInput(context);
                String result;
                if (wv.getSeletedIndex() > wv1Items.size() - 1 || wv1Items.get(wv.getSeletedIndex()).equals("无")) {
                    result = "";
                } else {
                    result = wv1Items.get(wv.getSeletedIndex());
                    if (wv2.getSeletedIndex() < wv2Items.size()) {
                        result += "," + wv2Items.get(wv2.getSeletedIndex());
                    }
                }
                onClickListener.onClick(view, -1, result, null, null);
                dialog.dismiss();
            }
        });
        showWheelViewDialog(outerView, dialog);
    }
}
